package main

import (
	"fmt"
	"net"
	"net/rpc"
	"net/rpc/jsonrpc"

	"gitlab.com/go-course-project/go15/skills/rpc/service"
)

func NewClient(address string) (*HelloServiceClient, error) {
	// 初始化一个客户端
	// 首先是通过rpc.Dial拨号RPC服务, 建立连接	conn, err := net.Dial(network, address)
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return nil, err
	}

	client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn))
	return &HelloServiceClient{
		c: client,
	}, nil
}

// 满足业务约束
var _ service.Service = (*HelloServiceClient)(nil)

type HelloServiceClient struct {
	c *rpc.Client
}

func (c *HelloServiceClient) Hello(req string, resp *string) error {
	err := c.c.Call("HelloService.Hello", req, &resp)
	if err != nil {
		return err
	}

	return nil
}

func main() {
	client, err := NewClient("localhost:1234")
	if err != nil {
		panic(err)
	}

	var resp string
	if err := client.Hello("bob", &resp); err != nil {
		panic(err)
	}
	fmt.Println(resp)
}
